<?php

/**
 * 限时提醒模型
 */
class Reminder_model extends CI_Model {
    
    const TN = "reminders";
    
    public function insert($reminder) {
        $this->db->insert(self::TN, $reminder);
    }
    
    /**
     * 按relation删除
     * @param type $rid
     */
    public function delete_batch_by_relation($relation_id) {
        $this->db->delete(self::TN, array('relation_id' => $relation_id));
    }
    
    /**
     * 
     * @param type $conditions
     * @param type $per_page 默认0表示取所有记录
     * @param type $page
     * @return array
     */
    public function fetch_array($conditions, $per_page = 0, $page = 0) {
        $this->_set_where($conditions);
        if ($per_page > 0) {
            $offset = ($page - 1) * $per_page;
            $this->db->limit($per_page, $offset);
        }

        return $this->db->get(self::TN)->result_array();
    }
    
    /**
     * 取需要提醒的记录
     * 截止日期前30天至截止日期，处理日期为空的记录
     */
    public function fetch_reminders() {
        $today = date('Y-m-d');
        $after_30_day = date('Y-m-d', time() + 24 * 3600 * 30);
        
        $sql = "select * from " . self::TN . 
                " where rm_operate_date = '' " .
                " and rm_receive_last_date <= '$after_30_day' " .
                " and rm_receive_last_date >= '$today' " .
                " order by rm_receive_last_date";
        $query = $this->db->query($sql);
        
        return $query->result_array();
    }

        /**
     * 设置where
     * @param type $conditions
     */
    private function _set_where($conditions) {
        if (isset($conditions['relation_id'])) {
            $this->db->where('relation_id', $conditions['relation_id']);
        }
    }
}

